import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:thinking/config/_.dart';
import 'package:thinking/event/_.dart';

/*
 * 动态申请App的权限
 */
class AuthorityApplication {




  /// App需要动态申请的权限
  static List<Permission> permissionList = [
    Permission.storage,
    Permission.photos
  ];

  static Future<bool> init({context}) async {
      Map<Permission, PermissionStatus> status = await permissionList.request();
      if (status[Permission.storage]!.isGranted) {
        Config.isPermission = true;
        Config.eventBus.fire(PermissionEvent(true));
        return true;
      } else if (status[Permission.storage]!.isDenied) {
        AuthorityApplication.showTips(
          context: context,
          content: "请允许App获取权限，否则App功能不能正常使用！",
          confirmText:'重新获取',
          confirmCall: () async {
            AuthorityApplication.init(context:context);
          },
        );
        Config.isPermission = false;
        return false;
      } else if (status[Permission.storage]!.isPermanentlyDenied) {
        AuthorityApplication.showTips(
          context: context,
          content: "您禁用了应用的必要权限，请到设置里开启！",
          confirmText: '打开设置',
          confirmCall: () async {
            await openAppSettings();
          },
        );
        Config.isPermission = false;
        return false;
      }else{

        return false;

      }
  }


  static Future showTips({
          context,
          content,
          confirmText,
          confirmCall
}) async{

    var result = await showCupertinoModalPopup(
      context: context, barrierDismissible:false,
      builder: (context){
        return CupertinoActionSheet(
          message: Text('$content',style: TextStyle(fontSize: 16.0,color: Colors.black87,fontWeight: FontWeight.w400),),
          actions: <Widget>[
            CupertinoActionSheetAction(

              child: Text(
                confirmText,
                style: TextStyle(color: ColorConfig.ThemeColor),
              ),
              onPressed: () {
                Navigator.of(context).pop('confirm');
              },
              isDefaultAction: true,
            ),
          ],
          cancelButton: CupertinoActionSheetAction(
            child: Text(
              '取消',
              style: TextStyle(color: ColorConfig.BlackBackColor),
            ),
            onPressed: () {
              Navigator.of(context).pop('cancel');
            },
          ),
        );
      }
    );
    if (result == 'confirm') {
      confirmCall();
    } else if (result == 'cancel') {
      Config.eventBus.fire(PermissionEvent(true));
      BotToast.showText(text: '您禁用了应用的必要权限，请到设置里开启！' );
    }
  }
}
